/******* 
 * @description: 获取HTTP类型
 * @param {String} url
 * @return {String}
 * @author: null
 */
function get_http_type(url) {
    var result = "http";

    if (url.indexOf("http") == 0 && url.startsWith("https")) {
        result = "https";
    }
    return result;
}

/******* 
 * @description: 获取header对象
 * @param {Array} headers
 * @return {Object}
 * @author: null
 */
function get_header_opts(headers) {
    let result = {}
    let line;
    for (let item in headers) {
        line = item.split(":");
        if (line.length != 2) continue;
        result[line[0]] = line[1];
    }
    return result;
}

if (globalThis.platform == "nodejs") {
    module.exports = {
        /******* 
         * @description: 创建response数据对象
         * @param {*}
         * @return {Object}
         * @author: null
         */        
        createResponseBuffer: function () {
            return {};
        },
        /******* 
         * @description: 释放response内存数据
         * @param {Object} resp
         * @return {*}
         * @author: null
         */        
        freeResponseBuffer: function (buffer) {
            buffer = null;
            return buffer;
        },
        /******* 
         * @description: 获取header
         * @param {Object} resp
         * @return {Object}
         * @author: null
         */        
        getResponseHeader: function(headers) {
            return headers;
        },
        /******* 
         * @description: 获取response数据
         * @param {Object} resp
         * @return {Buffer}
         * @author: null
         */        
        getResponseData: function (buffer) {
            return buffer ? Buffer.isBuffer(buffer) ? Buffer.from(buffer) : buffer : "";
        },
        /******* 
         * @description: 获取response数据长度
         * @param {Object} resp
         * @return {Integer}
         * @author: null
         */        
        getResponseLen: function (buffer) {
            return buffer ? Buffer.isBuffer(buffer) ? Buffer.from(buffer).length : buffer.length : 0;
        },
        /******* 
         * @description: 发送HTTP请求
         * @param {String} method
         * @param {String} url
         * @param {String / Array / Object} headers
         * @param {String} postData
         * @param {Integer} timeout
         * @param {Object} resp
         * @return {Integer}
         * @author: null
         */        
        request: function(method = "GET", url, headers, postData = null, responseType, timeout = null, __id__) {
            var type = get_http_type(url);
            let client = require("http");
            if (type == "https") client = require("https");

            let headerObj = null;
            var options = new URL(url);
            if (Array.isArray(headers)) { // 如果是数组，则遍历数组，将每一项以:拆分
                headerObj = get_header_opts(headers);
            } else if (Object.prototype.toString.call(headers) === "[object Object]") { // 如果是对象，则直接使用
                headerObj = headers;
            } else if (typeof headers === "string") { // 否如果是字符串，则先拆分为数组
                var headersArray = headers.split("\r\n");
                headerObj = get_header_opts(headersArray);
            } else {
                throw new Error("parameter headers is invaild, must be only one of Object / Array / String");
            }

            options.method = method;
            options.headers = headerObj;
            options.timeout = timeout;

            var req = client.request(options, function(res) {
                var buffer = "";
                // console.log(`STATUS: ${res.statusCode}`);
                // console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
                res.setEncoding("utf8");
                res.on("data", function(chunk) {
                    buffer += chunk;
                });
                res.on("end", function() {
                    // 通过索引号从globalThis获取回调函数
                    console.log(__id__)
                    if (!globalThis.eventbus.listeners[__id__]) {
                        throw new Error("can not get http client instance");
                    }

                    globalThis.eventbus.emit(__id__, "recv", [buffer, res.statusCode, res.headers])
                });
            });

            req.on("error", function() {});
            if (postData) req.write(postData);  // 将数据写入请求正文
            req.end();
        },
    };
}
